package com.ktg.mes.rec.service.impl;

import java.util.*;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONObject;
import com.ktg.common.utils.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.mes.md.domain.MdItem;
import com.ktg.mes.md.service.IMdItemService;
import com.ktg.mes.pro.domain.*;
import com.ktg.mes.pro.service.*;
import com.ktg.mes.rec.domain.RecProcessesExt;
import com.ktg.mes.rec.service.IRecProcessesExtService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktg.mes.rec.mapper.RecLnspectionRecordMapper;
import com.ktg.mes.rec.domain.RecLnspectionRecord;
import com.ktg.mes.rec.service.IRecLnspectionRecordService;



/**
 * 工序检测记录Service业务层处理
 *
 * @author byteco
 * @date 2022-11-04
 */
@Service
public class RecLnspectionRecordServiceImpl extends ServiceImpl<RecLnspectionRecordMapper, RecLnspectionRecord> implements IRecLnspectionRecordService
{
    @Autowired
    private RecLnspectionRecordMapper recLnspectionRecordMapper;
    @Autowired
    private IProProcessService proProcessService;

    @Autowired
    private IRecProcessesExtService recProcessesExtService;

    @Autowired
    private IProTaskService proTaskService;

    @Autowired
    private IMdItemService mdItemService;

    @Autowired
    private IProRouteProductService proRouteProductService;

    @Autowired
    private IProRouteProcessService proRouteProcessService;

    @Autowired
    private IProWaringService proWaringService;


    /**
     * 查询工序检测记录
     *
     * @param entity 工序检测记录
     * @param page 分页对象
     * @return 工序检测记录
     */
    @Override
    public IPage<RecLnspectionRecord> queryPageList(RecLnspectionRecord entity, Page<RecLnspectionRecord> page) {
        QueryWrapper<RecLnspectionRecord> lqw = new QueryWrapper<>(entity);
        lqw.orderByDesc("create_time");
        IPage<RecLnspectionRecord> pageList = this.page(page, lqw);
//        /** 查询工序名称 */
//        for (RecLnspectionRecord record : pageList.getRecords()) {
//            try {
//
//            }catch (Exception e){
//                record.setProcessesName("");
//            }
//
//        }
        return pageList;
    }

    /**
     * 查询工序检测记录
     *
     * @param entity 工序检测记录
     * @return 工序检测记录
     */
    @Override
    public List<RecLnspectionRecord> queryList(RecLnspectionRecord entity) {
        QueryWrapper<RecLnspectionRecord> lqw = new QueryWrapper<>(entity);
        lqw.orderByDesc("create_time");
        return this.list(lqw);
    }

    public RecLnspectionRecord getInfo(Long id)
    {
        QueryWrapper<RecLnspectionRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(RecLnspectionRecord::getId, id);
        return this.getOne(queryWrapper);
    }


    /**
     * 新增工序检测记录
     *
     * @param entity 工序检测记录
     * @return 结果
     */
    @Override
    public void insert(RecLnspectionRecord entity)
    {
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        this.save(entity);
    }


//    /**
//     * 判断工序参数是否超标，超标需要保存警告记录
//     * @param entity
//     */
//    @Override
//    public void isWarning(final RecLnspectionRecord entity,String desStr){
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                //提前设置需要警告的信息
//                ProWaring proWaring = new ProWaring();
//                proWaring.setType("1");
//                proWaring.setUpdateTime(new Date());
//                proWaring.setTaskName(entity.getTaskName());
//                proWaring.setBatchNo(entity.getBatchNo());
//                proWaring.setDeviceCode(entity.getMachineryCode());
//                proWaring.setDeviceName(entity.getMachineryName());
//                proWaring.setProcessName(entity.getProcessesName());
//                proWaring.setBucket(entity.getToolTypeName());
//                proWaring.setRecordId(entity.getId().toString());
//
//                try{
//
//                    //获取工序配置项实际参数值
//                    ProRouteProcess proRouteProcess = proRouteProcessService.getById(entity.getProcessesId());
//
//                    boolean isNeedWaring = false;
//                    String desString = desStr;
//                    if (proRouteProcess == null){
//                        isNeedWaring = true;
//                        desString = "工序配置数据获取失败！";
//                    }else {
//                        //获取工艺流程配置项，后台字段 对于 PDA字段
//                        RecProcessesExt recProcessesExt = new RecProcessesExt();
//                        recProcessesExt.setProcessId(entity.getProcessesId());
//                        QueryWrapper<RecProcessesExt> recProcessesExtQueryWrapper = new QueryWrapper<>();
//                        List<RecProcessesExt> mapList = recProcessesExtService.list(recProcessesExtQueryWrapper);
//
//                        //后台字段 对于 PDA字段
//                        Map<String,RecProcessesExt> mapPdaName = new HashMap<>();
//                        for (int i = 0; i < mapList.size(); i++) {
//                            JSONObject jsonObject = JSONObject.parseObject(mapList.get(i).getRuleBackstage());
//                            if (jsonObject != null && jsonObject.getString("type") != null){
//                                if (jsonObject.getString("type").equals("input")  || jsonObject.getString("type").equals("singleChoice")){
//                                    mapPdaName.put(mapList.get(i).getNameBackstage(),mapList.get(i));
//                                }
//                            }
//                        }
//
//
//                        if (entity.getDicText() == null){
//                            isNeedWaring = true;
//                            desString = "采集数据不能为空！";
//                        }else {
//                            JSONObject saveJsonObject = JSONObject.parseObject(entity.getDicText());
//                            if (saveJsonObject == null){
//                                saveJsonObject = new JSONObject();
//                            }
//
//                            JSONObject processJsonObject = JSONObject.parseObject(proRouteProcess.getParamJson());
//                            Set<String> processKeys = processJsonObject.keySet();
//
//
//                            for (String key: processKeys) {
//                                String value = processJsonObject.getString(key);
//                                if (value != null){
//                                    int a = value.indexOf("(");
//                                    if (a >= 0){
//                                        value = value.substring(0,a);
//                                    }
//                                }
//
//                                RecProcessesExt item = mapPdaName.get(key);
//                                if (item == null){
//                                    continue;
//                                }
//                                String padName = item.getName();
//
//                                if (StringUtils.isEmpty(padName)){
//                                    isNeedWaring = true;
//                                    desString = desString +"【"+key+"】没有配置采集参数的字段名称！";
//                                }else {
//                                    String saveValue = saveJsonObject.getString(padName);
//                                    if (saveValue != null){
//                                        int b = saveValue.indexOf("(");
//                                        if (b >= 0) {
//                                            saveValue = saveValue.substring(0, b);
//                                        }
//                                    }
//
//                                    if (value.startsWith("≤")){
//                                        //判断小于等于
//                                        if (StringUtils.isEmpty(saveValue)){
//                                            isNeedWaring = true;
//                                            desString = desString +"【"+padName+"】是"+value+",但此记录是空。";
//                                        }else {
//                                            if (Double.valueOf(saveValue.toString()) > Double.valueOf(value.replace("≤",""))){
//                                                isNeedWaring = true;
//                                                desString = desString +"【"+padName+"】是"+value+",但此记录是："+saveValue+"。";
//                                            }
//                                        }
//                                    }else if (value.startsWith("≥")){
//                                        //判断大于等于
//                                        if (StringUtils.isEmpty(saveValue)){
//                                            isNeedWaring = true;
//                                            desString = desString +"【"+padName+"】是"+value+",但此记录是空。";
//                                        }else {
//                                            if (Double.valueOf(saveValue.toString()) < Double.valueOf(value.replace("≥", ""))) {
//                                                isNeedWaring = true;
//                                                desString = desString +"【" + padName + "】是" + value + ",但此记录是：" + saveValue+"。";
//                                            }
//                                        }
//                                    }else if(value.equals("Y")){
//                                        //判断字段必须
//                                        if (StringUtils.isEmpty(saveValue) || saveValue.equals("0") || saveValue.equals("否")){
//                                            isNeedWaring = true;
//                                            if (StringUtils.isEmpty(saveValue)){
//                                                desString = desString +"【"+padName+"】是必须的,但此记录没有！";
//                                            }else {
//                                                desString = desString +"【"+padName+"】是必须的,但此记录是:"+saveValue+"。";
//                                            }
//
//                                        }
//                                    }else if(value.contains("-")){
//                                        String[] list1 = value.split("-");
//
//                                        double max = Double.valueOf(list1[1]).doubleValue();
//                                        double min = Double.valueOf(list1[0]).doubleValue();
//                                        if (saveValue == null){
//                                            isNeedWaring = true;
//                                            desString = desString +"【"+padName+"】是在"+min+"-"+max+"之间,但此记录是空。";
//                                        }else {
//                                            double tsValue = Double.valueOf(saveValue).doubleValue();
//                                            if (tsValue > max || tsValue < min){
//                                                isNeedWaring = true;
//                                                desString = desString +"【"+padName+"】是在"+min+"-"+max+"之间,但此记录是:"+saveValue+"。";
//                                            }
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
//
//                    if (isNeedWaring){
//                        proWaring.setDes(desString);
//                        proWaringService.insert(proWaring);
//                    }
//                }catch (Exception e){
//                    log.error("数据采集警报",e);
//                    String des = e.getLocalizedMessage();
//                    proWaring.setDes(des);
//                    proWaringService.insert(proWaring);
//                }
//            }
//        }).start();
//    }





    /**
     * 修改工序检测记录
     *
     * @param entity 工序检测记录
     * @return 结果
     */
    @Override
    public boolean update(RecLnspectionRecord entity)
    {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        boolean flag = this.updateById(entity);
        return flag;
    }

    /**
     * 批量删除工序检测记录
     *
     * @param ids 需要删除的工序检测记录主键
     * @return 结果
     */
    @Override
    public boolean delete(Long[] ids)
    {

        return this.removeByIds(Arrays.asList(ids));
    }

    /**
     * 删除工序检测记录信息
     *
     * @param id 工序检测记录主键
     * @return 结果
     */
    @Override
    public boolean delete(Long id)
    {
        return this.removeById(id);
    }


}
